package com.example.administrator.officeplatform.Activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baoyz.actionsheet.ActionSheet;
import com.example.administrator.officeplatform.MyApplication;
import com.example.administrator.officeplatform.R;
import com.example.administrator.officeplatform.adapter.PhotoAdapter;
import com.example.administrator.officeplatform.base.BaseActivity;
import com.example.administrator.officeplatform.bean.Fileinfo;
import com.example.administrator.officeplatform.bean.PersonInfo;
import com.example.administrator.officeplatform.bean.ReimbursementVoInfo;
import com.example.administrator.officeplatform.kj.AuditorActivity;
import com.example.administrator.officeplatform.kj.BMSearchActivity;
import com.example.administrator.officeplatform.kj.ImageScaleUtil;
import com.example.administrator.officeplatform.kj.IpUtil;
import com.example.administrator.officeplatform.kj.WorkflowConfigActivity;
import com.example.administrator.officeplatform.utils.DateUtil;
import com.example.administrator.officeplatform.utils.JsonUtil;
import com.example.administrator.officeplatform.utils.UILImageLoader;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StorageUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UpLoadImagesActivity extends BaseActivity implements View.OnClickListener{
    private PhotoAdapter photoAdapter;
    private List<PhotoInfo> mPhotoList;
    private int REQUEST_CODE_CAMERA=1;
    private final int REQUEST_CODE_GALLERY = 1001;
    private Integer startNum;
    private ProgressDialog mProgressDialog;
    private RecyclerView recyclerView;
    private Context mContext;
    final int DATE_DIALOG = 1;
    private OkHttpClient mOkHttpClient= new OkHttpClient();
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg");
    private List<Fileinfo> ls_file;
    private Intent mIntent;
    private ReimbursementVoInfo reimbursementVoInfo = new ReimbursementVoInfo();
    private TextView tv_upload;
    private Button btn_bc;
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_up_load_images);

    }

    @Override
    protected void initViews() {
        initConfig();
        init();
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tv_upload = (TextView)findViewById(R.id.tv_upload);
        btn_bc = (Button) findViewById(R.id.btn_bc);
        recyclerView=(RecyclerView)findViewById(R.id.rv_photo);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));// 布局管理器。
        recyclerView.setHasFixedSize(true);// 如果Item够简单，高度是确定的，打开FixSize将提高性能。
        recyclerView.setItemAnimator(new DefaultItemAnimator());//
    }

    @Override
    protected void initData() {
        mContext = this;
        mIntent = getIntent();
        mPhotoList = new ArrayList<>();
        ls_file = new ArrayList<>();
        toolbar.setTitle("上传图片");

        final PhotoInfo photoInfo = new PhotoInfo();
        mPhotoList.add(photoInfo);
        setRecyclerView();
        reimbursementVoInfo = (ReimbursementVoInfo) mIntent.getExtras().get(
                "ReimbursementVoInfo");
        ls_file = reimbursementVoInfo.getFileVoList();
    }

    @Override
    protected void initEvents() {
        btn_bc.setOnClickListener(this);
        tv_upload.setOnClickListener(this);
        toolbar.setNavigationOnClickListener(this);

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.tv_upload:
                if(mPhotoList.size()-1==0){
                    Toast.makeText(this, "请先拍照", Toast.LENGTH_SHORT).show();
                }else{
                    startNum=0;
                    String file = mPhotoList.get(startNum).getPhotoPath();
                    uploadPhoto(file);
                }
                break;

            case R.id.btn_bc:
                sendExpense();
                break;
            default:
                finish();
                break;
        }
    }



    /**
     *照相机框架配置
     *@author Wangzhiqiang
     *Created on 2017/12/18 14:14
     */
    private void initConfig() {
        //配置主题
        //ThemeConfig.CYAN
        ThemeConfig theme = new ThemeConfig.Builder()
                .build();
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(false)
                .build();

        //配置imageloader
        ImageLoader imageloader = new UILImageLoader();
        //设置核心配置信息
        CoreConfig coreConfig = new CoreConfig.Builder(getApplicationContext(), imageloader, theme)
                .setFunctionConfig(functionConfig)
                .build();
        GalleryFinal.init(coreConfig);
    }

    private void init() {
        File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3) // default
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir)) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(getApplicationContext())) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
    }
    /**
     *设置照片列表和点击事件
     *@author Wangzhiqiang
     *Created on 2017/12/18 15:28
     */
    private void setRecyclerView(){
        recyclerView.setAdapter(photoAdapter = new PhotoAdapter(this,mPhotoList));
        setRecyclerViewClick();
    }
    private void setRecyclerViewClick(){
        photoAdapter.setOnRecyclerViewListener(new PhotoAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(final int position) {
                if(position==mPhotoList.size()-1) {
//                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
//                        @Override
//                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
//                            if (resultList != null) {
//                                mPhotoList.add(0, resultList.get(0));
//                                setRecyclerView();
//                            }
//                        }
//
//                        @Override
//                        public void onHanlderFailure(int requestCode, String errorMsg) {
//                            Log.e("onHanlderFailure", "");
//                        }
//                    });
                    showActionSheet();

                }
            }

            @Override
            public boolean onItemLongClick(final int position) {
                if(position==mPhotoList.size()-1){
                }else{
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("提示");
                    builder.setMessage("确定要删除这张照片吗");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            mPhotoList.remove(position);
                            setRecyclerView();
                        }
                    });
                    builder.setNegativeButton("取消",null);
                    builder.show();

                }
                return false;
            }
        });
    }

    /**
     *拍照或从相册选择照片
     *@author Wangzhiqiang
     *Created on 2017/12/27 13:52
     */

    private void showActionSheet(){

        ActionSheet.createBuilder(mContext, getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("打开相册", "拍照")
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                        switch (index) {
                            case 0:
                                GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY,100, mOnHanlderResultCallback);
                                break;
                            case 1:
                                GalleryFinal.openCamera(REQUEST_CODE_CAMERA,mOnHanlderResultCallback);
                                break;
                            default:
                                break;
                        }
                    }
                })
                .show();
    }

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (resultList != null) {
                mPhotoList.addAll(0,resultList);
                setRecyclerView();

            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(mContext, errorMsg, Toast.LENGTH_SHORT).show();
        }
    };

    /**
     *上传图片
     *@author Wangzhiqiang
     *Created on 2017/12/18 15:31
     */
    private void uploadPhoto(String file){
        final String filename = DateUtil.getFileName();
        if(startNum==0){
            mProgressDialog = ProgressDialog.show(mContext, null, "正在上传中...");
        }
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
//        builder.addFormDataPart("reimbursement_image", filename, RequestBody.create(MEDIA_TYPE_PNG, new File(file)));
        builder.addFormDataPart("reimbursement_image", filename, RequestBody.create(MEDIA_TYPE_PNG, ImageScaleUtil.getBitmapByte(ImageScaleUtil.scaleImage(file))));
        //构建请求体
        RequestBody requestBody = builder.build();

        //构建请求
        Request request = new Request.Builder()
                .url(IpUtil.getAddress())//地址
                .post(requestBody)//添加请求体
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();
                String str = response.body().string();
                //{"filename":"IMG201712211342_007877-1513834924333.jpg"}
                if (str.indexOf("filename") >= 0) {
                    Fileinfo fileinfo = new Fileinfo();
                    String  filename = JsonUtil.getMsg(str,"filename");
                    fileinfo.setFileUrl(filename);
                    ls_file.add(fileinfo);
                    if (startNum == mPhotoList.size() - 2) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Integer num = startNum+1;
                                Toast.makeText(mContext, "第"+num+"张图片上传成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                        return;
                    } else {
                        startNum++;
                        String file = mPhotoList.get(startNum).getPhotoPath();
                        uploadPhoto(file);
                    }
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "图片上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                    ls_file=reimbursementVoInfo.getFileVoList();
                    return;
                }
            }
        });

    }
    /**
     *申请报销单数据请求
     *@author Wangzhiqiang
     *Created on 2017/12/21 10:21
     */
    private void sendExpense(){
        reimbursementVoInfo.setFileVoList(ls_file);
        reimbursementVoInfo.setEnclosureNum(String.valueOf(ls_file.size()));
        String json = JSON.toJSONString(reimbursementVoInfo);

        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mOkHttpClient = new OkHttpClient();

        RequestBody formBody =  FormBody.create(MediaType.parse("application/json;charset=UTF-8"),json);
        String s = MyApplication.getMsession();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement")
                .header("cookie", MyApplication.getMsession())
                .addHeader("Content-Type","application/json;charset=UTF-8")
                .put(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接服务器异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();

                final String str = response.body().string();
                //{"messageType":2,"type":"success","title":"操作信息","message":"提交成功","data":null}
                if(str.indexOf("success")>=0){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "修改成功", Toast.LENGTH_SHORT).show();
                            Intent mIntent = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("ReimbursementVoInfo", reimbursementVoInfo);
                            mIntent.putExtras(bundle);
                            //设置返回数据
                            setResult(1, mIntent);
                            finish();
                        }
                    });
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "修改失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        });
    }
}
